var express = require('express');
var path=require('path')
var webpack = require('webpack');
var compression = require('compression');
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackHotMiddleware = require('webpack-hot-middleware');
var proxy = require('http-proxy-middleware');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var config=require('./config/config');

var app = express();
var path = require('path')
var port = process.env.PORT || '3030';
// gzip压缩
app.use(compression());
app.set('view engine', 'hbs'); 
app.set('views',path.join( __dirname , '/views'));

app.use(session({
	store: new RedisStore({
		host:config.redis.host,
		port: config.redis.port,
		db:config.redis.db,
        password:config.redis.auth,
        ttl:60*60, //有效为1h
	}),
  secret: 'key_csbr',
  name:'csbr_id',//置cookie 保存的名称，默认是connect.sid
  cookie:config.cookie,//设置cookie 本地时间 ,domain:'localhost'
	resave:false,
    saveUninitialized:false,
    rolling:true
}));

var node_env=process.env.node_env.trim() || 'development';

if(node_env=='development'){
  var webpackConfig = require('./webpack.config');
  //webpackConfig.entry.app.unshift("webpack-hot-middleware/client?path=http://localhost:"+port+"/__webpack_hmr&reload=true&noInfo=false&quiet=false");
  webpackConfig.entry.app.push('webpack-hot-middleware/client?reload=true');
  const compiler = webpack(webpackConfig);
  app.use(webpackDevMiddleware(compiler,{
    noInfo: true,//配置webpack 生成日志
    //publicPath: 'http://localhost:'+port+'/' || webpackConfig.output.publicPath,
    publicPath:  webpackConfig.output.publicPath,
    headers: { "X-Custom-Header": "yes" },
    stats: {
        colors: true
    }
  }))
  app.use(webpackHotMiddleware(compiler));
  app.use(express.static(path.join(__dirname, 'src/')))
  
}else{
  app.get('/',function(req,res){
    res.render('index',{title:'vue-d',link:'webd'})
  })
}
app.use(express.static(path.join(__dirname, 'public/')))
require('./router/index')(app);
app.use('/', proxy({
  //target: 'http://61.149.254.126:8082/drugcloud_api', 
  target:'http://192.168.3.206:8082/drugcloud_api',
  changeOrigin: true,
  logLevel: 'debug',
  headers:{},
  pathRewrite:{
    '^/apis':'/token'// /apis/XX 请求替换成/token/xx
  },
  onProxyReq:function(proxyReq, req, res, options){
    // for(var i in proxyReq ){
    //   console.log(i,typeof proxyReq[i])
    // }
    // console.log(proxyReq.path)
  }
}));


module.exports=app;